package com.cn.steam.iam.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Map;

/**
 * @author: zjm
 * @create: 2021-11-14 19:35
 **/
@Service
public class Oauth2UserDetailService implements UserDetailsService {

    private static PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    private static Map<String,UserDetails> usersMap = Maps.newHashMap();

    static {
        UserDetails user = new UserDetails() {
            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                return Lists.newArrayList(new GrantedAuthority() {
                    @Override
                    public String getAuthority() {
                        return "test:add";
                    }
                });
            }

            @Override
            public String getPassword() {
                return passwordEncoder.encode("testuser");
            }

            @Override
            public String getUsername() {
                return "testuser";
            }

            @Override
            public boolean isAccountNonExpired() {
                return true;
            }

            @Override
            public boolean isAccountNonLocked() {
                return true;
            }

            @Override
            public boolean isCredentialsNonExpired() {
                return true;
            }

            @Override
            public boolean isEnabled() {
                return true;
            }
        };
        usersMap.put(user.getUsername(),user);
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return usersMap.get(s);
    }
}
